#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include "Log.hpp"

void Usage()
{
    std::cout << "Please Enter:\n"
              << "\tseverip  severport";
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
        exit(1);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // 创建套接字结构体
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    int n = inet_pton(AF_INET, ip.c_str(), &server.sin_addr);
    server.sin_port = htons(port);
    while (true)
    {
        // 创建套接字
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            Log(DEBUG, " create sockfd fail....");
            exit(2);
        }
        bool isreconnect = false;
        int cnt = 10;
        // 请求连接
        do
        {
            n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isreconnect = true;
                sleep(1);
                Log(WARNING, "already disconnect,please wait reconnect...%d", cnt--);
            }
            else
            {
                isreconnect = false;
                //Log(DEBUG, "connect success...");
            }
        } while (isreconnect && cnt);
        if(cnt==0)
        {
            Log(FATAL,"reconnect fail");
            exit(-1);
        }
        // 开始通信
        std::string request;
        char response[1024];
        std::cout<<"my say# ";
        getline(std::cin, request);
        n = write(sockfd, request.c_str(), request.size());
        if (n < 0)
        {
            Log(WARNING, "write fali...[%d][%s]", errno, strerror(errno));
        }
        n = read(sockfd, response, sizeof(response) - 1);
        if (n > 0)
        {
            response[n] = 0;
            std::cout << response << std::endl;
        }
    }
    return 0;
}